package me.zhengjie.modules.device.rest;

import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.device.domain.EnvironmentalDevice;
import me.zhengjie.modules.device.service.EnvironmentalDeviceService;
import me.zhengjie.modules.device.service.dto.EnvironmentalDeviceDTO;
import me.zhengjie.modules.device.service.query.EnvironmentalDeviceQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
* @author 张鹏
* @date 2019-05-08
*/
@RestController
@RequestMapping("api")
public class EnvironmentalDeviceController {

    @Autowired
    private EnvironmentalDeviceService environmentalDeviceService;

    @Autowired
    private EnvironmentalDeviceQueryService environmentalDeviceQueryService;

    private static final String ENTITY_NAME = "environmentalDevice";

    @Log("查询EnvironmentalDevice")
    @GetMapping(value = "/environmentalDevice")
    //@PreAuthorize("hasAnyRole('ADMIN')")
    public ResponseEntity getEnvironmentalDevices(EnvironmentalDeviceDTO resources, Pageable pageable){
        return new ResponseEntity(environmentalDeviceQueryService.queryAll(resources,pageable),HttpStatus.OK);
    }

    @Log("新增EnvironmentalDevice")
    @PostMapping(value = "/environmentalDevice")
    //@PreAuthorize("hasAnyRole('ADMIN')")
    public ResponseEntity create(@Validated @RequestBody EnvironmentalDevice resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        return new ResponseEntity(environmentalDeviceService.create(resources),HttpStatus.CREATED);
    }

    @Log("修改EnvironmentalDevice")
    @PutMapping(value = "/environmentalDevice")
    //@PreAuthorize("hasAnyRole('ADMIN')")
    public ResponseEntity update(@Validated @RequestBody EnvironmentalDevice resources){
        if (resources.getId() == null) {
            throw new BadRequestException(ENTITY_NAME +" ID Can not be empty");
        }
        environmentalDeviceService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("删除EnvironmentalDevice")
    @DeleteMapping(value = "/environmentalDevice/{id}")
    //@PreAuthorize("hasAnyRole('ADMIN')")
    public ResponseEntity delete(@PathVariable Long id){
        environmentalDeviceService.delete(id);
        return new ResponseEntity(HttpStatus.OK);
    }
}